3 * Holds shared logic for login and account creation pages.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
21 * @ingroup SpecialPage
24 use MediaWiki\Auth\AuthenticationRequest
;
25 use MediaWiki\Auth\AuthenticationResponse
;
26 use MediaWiki\Auth\AuthManager
;
27 use MediaWiki\Auth\Throttler
;
28 use MediaWiki\Logger\LoggerFactory
;
29 use MediaWiki\MediaWikiServices
;
30 use MediaWiki\Session\SessionManager
;
31 use Wikimedia\ScopedCallback
;
34 * Holds shared logic for login and account creation pages.
36 * @ingroup SpecialPage
38 abstract class LoginSignupSpecialPage
extends AuthManagerSpecialPage
{
43 protected $mReturnToQuery;
45 protected $mStickHTTPS;
47 protected $mEntryError = '';
48 protected $mEntryErrorType = 'error';
50 protected $mLoaded = false;
51 protected $mLoadedRequest = false;
52 protected $mSecureLoginUrl;
55 protected $securityLevel;
57 /** @var bool True if the user if creating an account for someone else. Flag used for internal
58 * communication, only set at the very end. */
59 protected $proxyAccountCreation;
60 /** @var User FIXME another flag for passing data. */
61 protected $targetUser;
66 /** @var FakeAuthTemplate */
67 protected $fakeTemplate;
69 abstract protected function isSignup();
72 * @param bool $direct True if the action was successful just now; false if that happened
73 * pre-redirection (so this handler was called already)
74 * @param StatusValue|null $extraMessages
77 abstract protected function successfulAction( $direct = false, $extraMessages = null );
80 * Logs to the authmanager-stats channel.
81 * @param bool $success
82 * @param string|null $status Error message key
84 abstract protected function logAuthResult( $success, $status = null );
86 public function __construct( $name ) {
87 global $wgUseMediaWikiUIEverywhere;
88 parent
::__construct( $name );
90 // Override UseMediaWikiEverywhere to true, to force login and create form to use mw ui
91 $wgUseMediaWikiUIEverywhere = true;
94 protected function setRequest( array $data, $wasPosted = null ) {
95 parent
::setRequest( $data, $wasPosted );
96 $this->mLoadedRequest
= false;
100 * Load basic request parameters for this Special page.
101 * @param string $subPage
103 private function loadRequestParameters( $subPage ) {
104 if ( $this->mLoadedRequest
) {
107 $this->mLoadedRequest
= true;
108 $request = $this->getRequest();
110 $this->mPosted
= $request->wasPosted();
111 $this->mIsReturn
= $subPage === 'return';
112 $this->mAction
= $request->getVal( 'action' );
113 $this->mFromHTTP
= $request->getBool( 'fromhttp', false )
114 ||
$request->getBool( 'wpFromhttp', false );
115 $this->mStickHTTPS
= ( !$this->mFromHTTP
&& $request->getProtocol() === 'https' )
116 ||
$request->getBool( 'wpForceHttps', false );
117 $this->mLanguage
= $request->getText( 'uselang' );
118 $this->mReturnTo
= $request->getVal( 'returnto', '' );
119 $this->mReturnToQuery
= $request->getVal( 'returntoquery', '' );
123 * Load data from request.
125 * @param string $subPage Subpage of Special:Userlogin
127 protected function load( $subPage ) {
128 global $wgSecureLogin;
130 $this->loadRequestParameters( $subPage );
131 if ( $this->mLoaded
) {
134 $this->mLoaded
= true;
135 $request = $this->getRequest();
137 $securityLevel = $this->getRequest()->getText( 'force' );
139 $securityLevel && AuthManager
::singleton()->securitySensitiveOperationStatus(
140 $securityLevel ) === AuthManager
::SEC_REAUTH
142 $this->securityLevel
= $securityLevel;
145 $this->loadAuth( $subPage );
147 $this->mToken
= $request->getVal( $this->getTokenName() );
149 // Show an error or warning passed on from a previous page
150 $entryError = $this->msg( $request->getVal( 'error', '' ) );
151 $entryWarning = $this->msg( $request->getVal( 'warning', '' ) );
152 // bc: provide login link as a parameter for messages where the translation
154 $loginreqlink = $this->getLinkRenderer()->makeKnownLink(
155 $this->getPageTitle(),
156 $this->msg( 'loginreqlink' )->text(),
159 'returnto' => $this->mReturnTo
,
160 'returntoquery' => $this->mReturnToQuery
,
161 'uselang' => $this->mLanguage ?
: null,
162 'fromhttp' => $wgSecureLogin && $this->mFromHTTP ?
'1' : null,
166 // Only show valid error or warning messages.
167 if ( $entryError->exists()
168 && in_array( $entryError->getKey(), LoginHelper
::getValidErrorMessages(), true )
170 $this->mEntryErrorType
= 'error';
171 $this->mEntryError
= $entryError->rawParams( $loginreqlink )->parse();
173 } elseif ( $entryWarning->exists()
174 && in_array( $entryWarning->getKey(), LoginHelper
::getValidErrorMessages(), true )
176 $this->mEntryErrorType
= 'warning';
177 $this->mEntryError
= $entryWarning->rawParams( $loginreqlink )->parse();
180 # 1. When switching accounts, it sucks to get automatically logged out
181 # 2. Do not return to PasswordReset after a successful password change
182 # but goto Wiki start page (Main_Page) instead ( T35997 )
183 $returnToTitle = Title
::newFromText( $this->mReturnTo
);
184 if ( is_object( $returnToTitle )
185 && ( $returnToTitle->isSpecial( 'Userlogout' )
186 ||
$returnToTitle->isSpecial( 'PasswordReset' ) )
188 $this->mReturnTo
= '';
189 $this->mReturnToQuery
= '';
193 protected function getPreservedParams( $withToken = false ) {
194 global $wgSecureLogin;
196 $params = parent
::getPreservedParams( $withToken );
198 'returnto' => $this->mReturnTo ?
: null,
199 'returntoquery' => $this->mReturnToQuery ?
: null,
201 if ( $wgSecureLogin && !$this->isSignup() ) {
202 $params['fromhttp'] = $this->mFromHTTP ?
'1' : null;
207 protected function beforeExecute( $subPage ) {
208 // finish initializing the class before processing the request - T135924
209 $this->loadRequestParameters( $subPage );
210 return parent
::beforeExecute( $subPage );
214 * @param string|null $subPage
216 public function execute( $subPage ) {
217 if ( $this->mPosted
) {
218 $time = microtime( true );
219 $profilingScope = new ScopedCallback( function () use ( $time ) {
220 $time = microtime( true ) - $time;
221 $statsd = MediaWikiServices
::getInstance()->getStatsdDataFactory();
222 $statsd->timing( "timing.login.ui.{$this->authAction}", $time * 1000 );
226 $authManager = AuthManager
::singleton();
227 $session = SessionManager
::getGlobalSession();
229 // Session data is used for various things in the authentication process, so we must make
230 // sure a session cookie or some equivalent mechanism is set.
233 $this->load( $subPage );
235 $this->checkPermissions();
237 // Make sure the system configuration allows log in / sign up
238 if ( !$this->isSignup() && !$authManager->canAuthenticateNow() ) {
239 if ( !$session->canSetUser() ) {
240 throw new ErrorPageError( 'cannotloginnow-title', 'cannotloginnow-text', [
241 $session->getProvider()->describe( RequestContext
::getMain()->getLanguage() )
244 throw new ErrorPageError( 'cannotlogin-title', 'cannotlogin-text' );
245 } elseif ( $this->isSignup() && !$authManager->canCreateAccounts() ) {
246 throw new ErrorPageError( 'cannotcreateaccount-title', 'cannotcreateaccount-text' );
250 * In the case where the user is already logged in, and was redirected to
251 * the login form from a page that requires login, do not show the login
252 * page. The use case scenario for this is when a user opens a large number
253 * of tabs, is redirected to the login page on all of them, and then logs
254 * in on one, expecting all the others to work properly.
256 * However, do show the form if it was visited intentionally (no 'returnto'
257 * is present). People who often switch between several accounts have grown
258 * accustomed to this behavior.
260 * Also make an exception when force=<level> is set in the URL, which means the user must
261 * reauthenticate for security reasons.
263 if ( !$this->isSignup() && !$this->mPosted
&& !$this->securityLevel
&&
264 ( $this->mReturnTo
!== '' ||
$this->mReturnToQuery
!== '' ) &&
265 $this->getUser()->isLoggedIn()
267 $this->successfulAction();
270 // If logging in and not on HTTPS, either redirect to it or offer a link.
271 global $wgSecureLogin;
272 if ( $this->getRequest()->getProtocol() !== 'https' ) {
273 $title = $this->getFullTitle();
274 $query = $this->getPreservedParams( false ) +
[
276 ( $this->mEntryErrorType
=== 'error' ?
'error'
277 : 'warning' ) => $this->mEntryError
,
278 ] +
$this->getRequest()->getQueryValues();
279 $url = $title->getFullURL( $query, false, PROTO_HTTPS
);
280 if ( $wgSecureLogin && !$this->mFromHTTP
&&
281 wfCanIPUseHTTPS( $this->getRequest()->getIP() )
283 // Avoid infinite redirect
284 $url = wfAppendQuery( $url, 'fromhttp=1' );
285 $this->getOutput()->redirect( $url );
286 // Since we only do this redir to change proto, always vary
287 $this->getOutput()->addVaryHeader( 'X-Forwarded-Proto' );
291 // A wiki without HTTPS login support should set $wgServer to
292 // http://somehost, in which case the secure URL generated
293 // above won't actually start with https://
294 if ( substr( $url, 0, 8 ) === 'https://' ) {
295 $this->mSecureLoginUrl
= $url;
300 if ( !$this->isActionAllowed( $this->authAction
) ) {
301 // FIXME how do we explain this to the user? can we handle session loss better?
302 // messages used: authpage-cannot-login, authpage-cannot-login-continue,
303 // authpage-cannot-create, authpage-cannot-create-continue
304 $this->mainLoginForm( [], 'authpage-cannot-' . $this->authAction
);
308 if ( $this->canBypassForm( $button_name ) ) {
309 $this->setRequest( [], true );
310 $this->getRequest()->setVal( $this->getTokenName(), $this->getToken() );
311 if ( $button_name ) {
312 $this->getRequest()->setVal( $button_name, true );
316 $status = $this->trySubmit();
318 if ( !$status ||
!$status->isGood() ) {
319 $this->mainLoginForm( $this->authRequests
, $status ?
$status->getMessage() : '', 'error' );
323 /** @var AuthenticationResponse $response */
324 $response = $status->getValue();
326 $returnToUrl = $this->getPageTitle( 'return' )
327 ->getFullURL( $this->getPreservedParams( true ), false, PROTO_HTTPS
);
328 switch ( $response->status
) {
329 case AuthenticationResponse
::PASS
:
330 $this->logAuthResult( true );
331 $this->proxyAccountCreation
= $this->isSignup() && !$this->getUser()->isAnon();
332 $this->targetUser
= User
::newFromName( $response->username
);
335 !$this->proxyAccountCreation
336 && $response->loginRequest
337 && $authManager->canAuthenticateNow()
339 // successful registration; log the user in instantly
340 $response2 = $authManager->beginAuthentication( [ $response->loginRequest
],
342 if ( $response2->status
!== AuthenticationResponse
::PASS
) {
343 LoggerFactory
::getInstance( 'login' )
344 ->error( 'Could not log in after account creation' );
345 $this->successfulAction( true, Status
::newFatal( 'createacct-loginerror' ) );
350 if ( !$this->proxyAccountCreation
) {
351 // Ensure that the context user is the same as the session user.
352 $this->setSessionUserForCurrentRequest();
355 $this->successfulAction( true );
357 case AuthenticationResponse
::FAIL
:
359 case AuthenticationResponse
::RESTART
:
360 unset( $this->authForm
);
361 if ( $response->status
=== AuthenticationResponse
::FAIL
) {
362 $action = $this->getDefaultAction( $subPage );
363 $messageType = 'error';
365 $action = $this->getContinueAction( $this->authAction
);
366 $messageType = 'warning';
368 $this->logAuthResult( false, $response->message ?
$response->message
->getKey() : '-' );
369 $this->loadAuth( $subPage, $action, true );
370 $this->mainLoginForm( $this->authRequests
, $response->message
, $messageType );
372 case AuthenticationResponse
::REDIRECT
:
373 unset( $this->authForm
);
374 $this->getOutput()->redirect( $response->redirectTarget
);
376 case AuthenticationResponse
::UI
:
377 unset( $this->authForm
);
378 $this->authAction
= $this->isSignup() ? AuthManager
::ACTION_CREATE_CONTINUE
379 : AuthManager
::ACTION_LOGIN_CONTINUE
;
380 $this->authRequests
= $response->neededRequests
;
381 $this->mainLoginForm( $response->neededRequests
, $response->message
, $response->messageType
);
384 throw new LogicException( 'invalid AuthenticationResponse' );
389 * Determine if the login form can be bypassed. This will be the case when no more than one
390 * button is present and no other user input fields that are not marked as 'skippable' are
391 * present. If the login form were not bypassed, the user would be presented with a
392 * superfluous page on which they must press the single button to proceed with login.
393 * Not only does this cause an additional mouse click and page load, it confuses users,
394 * especially since there are a help link and forgotten password link that are
395 * provided on the login page that do not apply to this situation.
397 * @param string|null &$button_name if the form has a single button, returns
398 * the name of the button; otherwise, returns null
401 private function canBypassForm( &$button_name ) {
403 if ( $this->isContinued() ) {
406 $fields = AuthenticationRequest
::mergeFieldInfo( $this->authRequests
);
407 foreach ( $fields as $fieldname => $field ) {
408 if ( !isset( $field['type'] ) ) {
411 if ( !empty( $field['skippable'] ) ) {
414 if ( $field['type'] === 'button' ) {
415 if ( $button_name !== null ) {
419 $button_name = $fieldname;
421 } elseif ( $field['type'] !== 'null' ) {
429 * Show the success page.
431 * @param string $type Condition of return to; see `executeReturnTo`
432 * @param string|Message $title Page's title
433 * @param string $msgname
434 * @param string $injected_html
435 * @param StatusValue|null $extraMessages
437 protected function showSuccessPage(
438 $type, $title, $msgname, $injected_html, $extraMessages
440 $out = $this->getOutput();
441 $out->setPageTitle( $title );
443 $out->addWikiMsg( $msgname, wfEscapeWikiText( $this->getUser()->getName() ) );
445 if ( $extraMessages ) {
446 $extraMessages = Status
::wrap( $extraMessages );
447 $out->addWikiText( $extraMessages->getWikiText() );
450 $out->addHTML( $injected_html );
452 $helper = new LoginHelper( $this->getContext() );
453 $helper->showReturnToPage( $type, $this->mReturnTo
, $this->mReturnToQuery
, $this->mStickHTTPS
);
457 * Add a "return to" link or redirect to it.
458 * Extensions can use this to reuse the "return to" logic after
459 * inject steps (such as redirection) into the login process.
461 * @param string $type One of the following:
462 * - error: display a return to link ignoring $wgRedirectOnLogin
463 * - signup: display a return to link using $wgRedirectOnLogin if needed
464 * - success: display a return to link using $wgRedirectOnLogin if needed
465 * - successredirect: send an HTTP redirect using $wgRedirectOnLogin if needed
466 * @param string $returnTo
467 * @param array|string $returnToQuery
468 * @param bool $stickHTTPS Keep redirect link on HTTPS
471 public function showReturnToPage(
472 $type, $returnTo = '', $returnToQuery = '', $stickHTTPS = false
474 $helper = new LoginHelper( $this->getContext() );
475 $helper->showReturnToPage( $type, $returnTo, $returnToQuery, $stickHTTPS );
479 * Replace some globals to make sure the fact that the user has just been logged in is
480 * reflected in the current request.
482 protected function setSessionUserForCurrentRequest() {
483 global $wgUser, $wgLang;
485 $context = RequestContext
::getMain();
486 $localContext = $this->getContext();
487 if ( $context !== $localContext ) {
488 // remove AuthManagerSpecialPage context hack
489 $this->setContext( $context );
492 $user = $context->getRequest()->getSession()->getUser();
495 $context->setUser( $user );
497 $code = $this->getRequest()->getVal( 'uselang', $user->getOption( 'language' ) );
498 $userLang = Language
::factory( $code );
500 $context->setLanguage( $userLang );
504 * @param AuthenticationRequest[] $requests A list of AuthorizationRequest objects,
505 * used to generate the form fields. An empty array means a fatal error
506 * (authentication cannot continue).
507 * @param string|Message $msg
508 * @param string $msgtype
509 * @throws ErrorPageError
512 * @throws MWException
513 * @throws PermissionsError
514 * @throws ReadOnlyError
517 protected function mainLoginForm( array $requests, $msg = '', $msgtype = 'error' ) {
518 $user = $this->getUser();
519 $out = $this->getOutput();
521 // FIXME how to handle empty $requests - restart, or no form, just an error message?
522 // no form would be better for no session type errors, restart is better when can* fails.
524 $this->authAction
= $this->getDefaultAction( $this->subPage
);
525 $this->authForm
= null;
526 $requests = AuthManager
::singleton()->getAuthenticationRequests( $this->authAction
, $user );
529 // Generic styles and scripts for both login and signup form
530 $out->addModuleStyles( [
532 'mediawiki.ui.button',
533 'mediawiki.ui.checkbox',
534 'mediawiki.ui.input',
535 'mediawiki.special.userlogin.common.styles'
537 if ( $this->isSignup() ) {
538 // XXX hack pending RL or JS parse() support for complex content messages T27349
539 $out->addJsConfigVars( 'wgCreateacctImgcaptchaHelp',
540 $this->msg( 'createacct-imgcaptcha-help' )->parse() );
542 // Additional styles and scripts for signup form
544 'mediawiki.special.userlogin.signup.js'
546 $out->addModuleStyles( [
547 'mediawiki.special.userlogin.signup.styles'
550 // Additional styles for login form
551 $out->addModuleStyles( [
552 'mediawiki.special.userlogin.login.styles'
555 $out->disallowUserJs(); // just in case...
557 $form = $this->getAuthForm( $requests, $this->authAction
, $msg, $msgtype );
558 $form->prepareForm();
560 $submitStatus = Status
::newGood();
561 if ( $msg && $msgtype === 'warning' ) {
562 $submitStatus->warning( $msg );
563 } elseif ( $msg && $msgtype === 'error' ) {
564 $submitStatus->fatal( $msg );
567 // warning header for non-standard workflows (e.g. security reauthentication)
569 !$this->isSignup() &&
570 $this->getUser()->isLoggedIn() &&
571 $this->authAction
!== AuthManager
::ACTION_LOGIN_CONTINUE
573 $reauthMessage = $this->securityLevel ?
'userlogin-reauth' : 'userlogin-loggedin';
574 $submitStatus->warning( $reauthMessage, $this->getUser()->getName() );
577 $formHtml = $form->getHTML( $submitStatus );
579 $out->addHTML( $this->getPageHtml( $formHtml ) );
583 * Add page elements which are outside the form.
584 * FIXME this should probably be a template, but use a sane language (handlebars?)
585 * @param string $formHtml
588 protected function getPageHtml( $formHtml ) {
589 global $wgLoginLanguageSelector;
591 $loginPrompt = $this->isSignup() ?
'' : Html
::rawElement( 'div',
592 [ 'id' => 'userloginprompt' ], $this->msg( 'loginprompt' )->parseAsBlock() );
593 $languageLinks = $wgLoginLanguageSelector ?
$this->makeLanguageSelector() : '';
594 $signupStartMsg = $this->msg( 'signupstart' );
595 $signupStart = ( $this->isSignup() && !$signupStartMsg->isDisabled() )
596 ? Html
::rawElement( 'div', [ 'id' => 'signupstart' ], $signupStartMsg->parseAsBlock() ) : '';
597 if ( $languageLinks ) {
598 $languageLinks = Html
::rawElement( 'div', [ 'id' => 'languagelinks' ],
599 Html
::rawElement( 'p', [], $languageLinks )
603 $benefitsContainer = '';
604 if ( $this->isSignup() && $this->showExtraInformation() ) {
606 // createacct-benefit-icon1 createacct-benefit-head1 createacct-benefit-body1
607 // createacct-benefit-icon2 createacct-benefit-head2 createacct-benefit-body2
608 // createacct-benefit-icon3 createacct-benefit-head3 createacct-benefit-body3
611 for ( $benefitIdx = 1; $benefitIdx <= $benefitCount; $benefitIdx++
) {
612 $headUnescaped = $this->msg( "createacct-benefit-head$benefitIdx" )->text();
613 $iconClass = $this->msg( "createacct-benefit-icon$benefitIdx" )->escaped();
614 $benefitList .= Html
::rawElement( 'div', [ 'class' => "mw-number-text $iconClass" ],
615 Html
::rawElement( 'h3', [],
616 $this->msg( "createacct-benefit-head$benefitIdx" )->escaped()
618 . Html
::rawElement( 'p', [],
619 $this->msg( "createacct-benefit-body$benefitIdx" )->params( $headUnescaped )->escaped()
623 $benefitsContainer = Html
::rawElement( 'div', [ 'class' => 'mw-createacct-benefits-container' ],
624 Html
::rawElement( 'h2', [], $this->msg( 'createacct-benefit-heading' )->escaped() )
625 . Html
::rawElement( 'div', [ 'class' => 'mw-createacct-benefits-list' ],
631 $html = Html
::rawElement( 'div', [ 'class' => 'mw-ui-container' ],
635 . Html
::rawElement( 'div', [ 'id' => 'userloginForm' ],
645 * Generates a form from the given request.
646 * @param AuthenticationRequest[] $requests
647 * @param string $action AuthManager action name
648 * @param string|Message $msg
649 * @param string $msgType
652 protected function getAuthForm( array $requests, $action, $msg = '', $msgType = 'error' ) {
653 global $wgSecureLogin;
654 // FIXME merge this with parent
656 if ( isset( $this->authForm
) ) {
657 return $this->authForm
;
660 $usingHTTPS = $this->getRequest()->getProtocol() === 'https';
662 // get basic form description from the auth logic
663 $fieldInfo = AuthenticationRequest
::mergeFieldInfo( $requests );
664 $fakeTemplate = $this->getFakeTemplate( $msg, $msgType );
665 $this->fakeTemplate
= $fakeTemplate; // FIXME there should be a saner way to pass this to the hook
666 // this will call onAuthChangeFormFields()
667 $formDescriptor = static::fieldInfoToFormDescriptor( $requests, $fieldInfo, $this->authAction
);
668 $this->postProcessFormDescriptor( $formDescriptor, $requests );
670 $context = $this->getContext();
671 if ( $context->getRequest() !== $this->getRequest() ) {
672 // We have overridden the request, need to make sure the form uses that too.
673 $context = new DerivativeContext( $this->getContext() );
674 $context->setRequest( $this->getRequest() );
676 $form = HTMLForm
::factory( 'vform', $formDescriptor, $context );
678 $form->addHiddenField( 'authAction', $this->authAction
);
679 if ( $this->mLanguage
) {
680 $form->addHiddenField( 'uselang', $this->mLanguage
);
682 $form->addHiddenField( 'force', $this->securityLevel
);
683 $form->addHiddenField( $this->getTokenName(), $this->getToken()->toString() );
684 if ( $wgSecureLogin ) {
685 // If using HTTPS coming from HTTP, then the 'fromhttp' parameter must be preserved
686 if ( !$this->isSignup() ) {
687 $form->addHiddenField( 'wpForceHttps', (int)$this->mStickHTTPS
);
688 $form->addHiddenField( 'wpFromhttp', $usingHTTPS );
692 // set properties of the form itself
693 $form->setAction( $this->getPageTitle()->getLocalURL( $this->getReturnToQueryStringFragment() ) );
694 $form->setName( 'userlogin' . ( $this->isSignup() ?
'2' : '' ) );
695 if ( $this->isSignup() ) {
696 $form->setId( 'userlogin2' );
699 $form->suppressDefaultSubmit();
701 $this->authForm
= $form;
707 * Temporary B/C method to handle extensions using the UserLoginForm/UserCreateForm hooks.
708 * @param string|Message $msg
709 * @param string $msgType
710 * @return FakeAuthTemplate
712 protected function getFakeTemplate( $msg, $msgType ) {
713 global $wgAuth, $wgEnableEmail, $wgHiddenPrefs, $wgEmailConfirmToEdit, $wgEnableUserEmail,
714 $wgSecureLogin, $wgPasswordResetRoutes;
716 // make a best effort to get the value of fields which used to be fixed in the old login
717 // template but now might or might not exist depending on what providers are used
718 $request = $this->getRequest();
720 'mUsername' => $request->getText( 'wpName' ),
721 'mPassword' => $request->getText( 'wpPassword' ),
722 'mRetype' => $request->getText( 'wpRetype' ),
723 'mEmail' => $request->getText( 'wpEmail' ),
724 'mRealName' => $request->getText( 'wpRealName' ),
725 'mDomain' => $request->getText( 'wpDomain' ),
726 'mReason' => $request->getText( 'wpReason' ),
727 'mRemember' => $request->getCheck( 'wpRemember' ),
730 // Preserves a bunch of logic from the old code that was rewritten in getAuthForm().
731 // There is no code reuse to make this easier to remove .
732 // If an extension tries to change any of these values, they are out of luck - we only
733 // actually use the domain/usedomain/domainnames, extraInput and extrafields keys.
735 $titleObj = $this->getPageTitle();
736 $user = $this->getUser();
737 $template = new FakeAuthTemplate();
739 // Pre-fill username (if not creating an account, T46775).
740 if ( $data->mUsername
== '' && $this->isSignup() ) {
741 if ( $user->isLoggedIn() ) {
742 $data->mUsername
= $user->getName();
744 $data->mUsername
= $this->getRequest()->getSession()->suggestLoginUsername();
748 if ( $this->isSignup() ) {
749 // Must match number of benefits defined in messages
750 $template->set( 'benefitCount', 3 );
752 $q = 'action=submitlogin&type=signup';
753 $linkq = 'type=login';
755 $q = 'action=submitlogin&type=login';
756 $linkq = 'type=signup';
759 if ( $this->mReturnTo
!== '' ) {
760 $returnto = '&returnto=' . wfUrlencode( $this->mReturnTo
);
761 if ( $this->mReturnToQuery
!== '' ) {
762 $returnto .= '&returntoquery=' .
763 wfUrlencode( $this->mReturnToQuery
);
769 # Don't show a "create account" link if the user can't.
770 if ( $this->showCreateAccountLink() ) {
771 # Pass any language selection on to the mode switch link
772 if ( $this->mLanguage
) {
773 $linkq .= '&uselang=' . urlencode( $this->mLanguage
);
775 // Supply URL, login template creates the button.
776 $template->set( 'createOrLoginHref', $titleObj->getLocalURL( $linkq ) );
778 $template->set( 'link', '' );
781 $resetLink = $this->isSignup()
783 : is_array( $wgPasswordResetRoutes )
784 && in_array( true, array_values( $wgPasswordResetRoutes ), true );
786 $template->set( 'header', '' );
787 $template->set( 'formheader', '' );
788 $template->set( 'skin', $this->getSkin() );
790 $template->set( 'name', $data->mUsername
);
791 $template->set( 'password', $data->mPassword
);
792 $template->set( 'retype', $data->mRetype
);
793 $template->set( 'createemailset', false ); // no easy way to get that from AuthManager
794 $template->set( 'email', $data->mEmail
);
795 $template->set( 'realname', $data->mRealName
);
796 $template->set( 'domain', $data->mDomain
);
797 $template->set( 'reason', $data->mReason
);
798 $template->set( 'remember', $data->mRemember
);
800 $template->set( 'action', $titleObj->getLocalURL( $q ) );
801 $template->set( 'message', $msg );
802 $template->set( 'messagetype', $msgType );
803 $template->set( 'createemail', $wgEnableEmail && $user->isLoggedIn() );
804 $template->set( 'userealname', !in_array( 'realname', $wgHiddenPrefs, true ) );
805 $template->set( 'useemail', $wgEnableEmail );
806 $template->set( 'emailrequired', $wgEmailConfirmToEdit );
807 $template->set( 'emailothers', $wgEnableUserEmail );
808 $template->set( 'canreset', $wgAuth->allowPasswordChange() );
809 $template->set( 'resetlink', $resetLink );
810 $template->set( 'canremember', $request->getSession()->getProvider()
811 ->getRememberUserDuration() !== null );
812 $template->set( 'usereason', $user->isLoggedIn() );
813 $template->set( 'cansecurelogin', ( $wgSecureLogin ) );
814 $template->set( 'stickhttps', (int)$this->mStickHTTPS
);
815 $template->set( 'loggedin', $user->isLoggedIn() );
816 $template->set( 'loggedinuser', $user->getName() );
817 $template->set( 'token', $this->getToken()->toString() );
819 $action = $this->isSignup() ?
'signup' : 'login';
820 $wgAuth->modifyUITemplate( $template, $action );
822 $oldTemplate = $template;
824 // Both Hooks::run are explicit here to make findHooks.php happy
825 if ( $this->isSignup() ) {
826 Hooks
::run( 'UserCreateForm', [ &$template ] );
827 if ( $oldTemplate !== $template ) {
828 wfDeprecated( "reference in UserCreateForm hook", '1.27' );
831 Hooks
::run( 'UserLoginForm', [ &$template ] );
832 if ( $oldTemplate !== $template ) {
833 wfDeprecated( "reference in UserLoginForm hook", '1.27' );
840 public function onAuthChangeFormFields(
841 array $requests, array $fieldInfo, array &$formDescriptor, $action
843 $coreFieldDescriptors = $this->getFieldDefinitions( $this->fakeTemplate
);
844 $specialFields = array_merge( [ 'extraInput' ],
845 array_keys( $this->fakeTemplate
->getExtraInputDefinitions() ) );
847 // keep the ordering from getCoreFieldDescriptors() where there is no explicit weight
848 foreach ( $coreFieldDescriptors as $fieldName => $coreField ) {
849 $requestField = $formDescriptor[$fieldName] ??
[];
851 // remove everything that is not in the fieldinfo, is not marked as a supplemental field
852 // to something in the fieldinfo, is not B/C for the pre-AuthManager templates,
853 // and is not an info field or a submit button
855 !isset( $fieldInfo[$fieldName] )
857 !isset( $coreField['baseField'] )
858 ||
!isset( $fieldInfo[$coreField['baseField']] )
860 && !in_array( $fieldName, $specialFields, true )
862 !isset( $coreField['type'] )
863 ||
!in_array( $coreField['type'], [ 'submit', 'info' ], true )
866 $coreFieldDescriptors[$fieldName] = null;
870 // core message labels should always take priority
872 isset( $coreField['label'] )
873 ||
isset( $coreField['label-message'] )
874 ||
isset( $coreField['label-raw'] )
876 unset( $requestField['label'], $requestField['label-message'], $coreField['label-raw'] );
879 $coreFieldDescriptors[$fieldName] +
= $requestField;
882 $formDescriptor = array_filter( $coreFieldDescriptors +
$formDescriptor );
887 * Show extra information such as password recovery information, link from login to signup,
888 * CTA etc? Such information should only be shown on the "landing page", ie. when the user
889 * is at the first step of the authentication process.
892 protected function showExtraInformation() {
893 return $this->authAction
!== $this->getContinueAction( $this->authAction
)
894 && !$this->securityLevel
;
898 * Create a HTMLForm descriptor for the core login fields.
899 * @param FakeAuthTemplate $template B/C data (not used but needed by getBCFieldDefinitions)
902 protected function getFieldDefinitions( $template ) {
903 global $wgEmailConfirmToEdit;
905 $isLoggedIn = $this->getUser()->isLoggedIn();
906 $continuePart = $this->isContinued() ?
'continue-' : '';
907 $anotherPart = $isLoggedIn ?
'another-' : '';
908 $expiration = $this->getRequest()->getSession()->getProvider()->getRememberUserDuration();
909 $expirationDays = ceil( $expiration / ( 3600 * 24 ) );
910 $secureLoginLink = '';
911 if ( $this->mSecureLoginUrl
) {
912 $secureLoginLink = Html
::element( 'a', [
913 'href' => $this->mSecureLoginUrl
,
914 'class' => 'mw-ui-flush-right mw-secure',
915 ], $this->msg( 'userlogin-signwithsecure' )->text() );
917 $usernameHelpLink = '';
918 if ( !$this->msg( 'createacct-helpusername' )->isDisabled() ) {
919 $usernameHelpLink = Html
::rawElement( 'span', [
920 'class' => 'mw-ui-flush-right',
921 ], $this->msg( 'createacct-helpusername' )->parse() );
924 if ( $this->isSignup() ) {
925 $fieldDefinitions = [
927 // used by the mediawiki.special.userlogin.signup.js module for error display
928 // FIXME merge this with HTMLForm's normal status (error) area
931 'default' => Html
::element( 'div', [ 'id' => 'mw-createacct-status-area' ] ),
935 'label-raw' => $this->msg( 'userlogin-yourname' )->escaped() . $usernameHelpLink,
937 'placeholder-message' => $isLoggedIn ?
'createacct-another-username-ph'
938 : 'userlogin-yourname-ph',
941 // create account without providing password, a temporary one will be mailed
943 'label-message' => 'createaccountmail',
944 'name' => 'wpCreateaccountMail',
945 'id' => 'wpCreateaccountMail',
948 'id' => 'wpPassword2',
949 'placeholder-message' => 'createacct-yourpassword-ph',
950 'hide-if' => [ '===', 'wpCreateaccountMail', '1' ],
954 'baseField' => 'password',
955 'type' => 'password',
956 'label-message' => 'createacct-yourpasswordagain',
958 'cssclass' => 'loginPassword',
960 'validation-callback' => function ( $value, $alldata ) {
961 if ( empty( $alldata['mailpassword'] ) && !empty( $alldata['password'] ) ) {
963 return $this->msg( 'htmlform-required' );
964 } elseif ( $value !== $alldata['password'] ) {
965 return $this->msg( 'badretype' );
970 'hide-if' => [ '===', 'wpCreateaccountMail', '1' ],
971 'placeholder-message' => 'createacct-yourpasswordagain-ph',
975 'label-message' => $wgEmailConfirmToEdit ?
'createacct-emailrequired'
976 : 'createacct-emailoptional',
978 'cssclass' => 'loginText',
980 // FIXME will break non-standard providers
981 'required' => $wgEmailConfirmToEdit,
982 'validation-callback' => function ( $value, $alldata ) {
983 global $wgEmailConfirmToEdit;
985 // AuthManager will check most of these, but that will make the auth
986 // session fail and this won't, so nicer to do it this way
987 if ( !$value && $wgEmailConfirmToEdit ) {
988 // no point in allowing registration without email when email is
990 return $this->msg( 'noemailtitle' );
991 } elseif ( !$value && !empty( $alldata['mailpassword'] ) ) {
992 // cannot send password via email when there is no email address
993 return $this->msg( 'noemailcreate' );
994 } elseif ( $value && !Sanitizer
::validateEmail( $value ) ) {
995 return $this->msg( 'invalidemailaddress' );
999 'placeholder-message' => 'createacct-' . $anotherPart . 'email-ph',
1003 'help-message' => $isLoggedIn ?
'createacct-another-realname-tip'
1004 : 'prefs-help-realname',
1005 'label-message' => 'createacct-realname',
1006 'cssclass' => 'loginText',
1008 'id' => 'wpRealName',
1011 // comment for the user creation log
1013 'label-message' => 'createacct-reason',
1014 'cssclass' => 'loginText',
1017 'placeholder-message' => 'createacct-reason-ph',
1019 'extrainput' => [], // placeholder for fields coming from the template
1020 'createaccount' => [
1023 'default' => $this->msg( 'createacct-' . $anotherPart . $continuePart .
1025 'name' => 'wpCreateaccount',
1026 'id' => 'wpCreateaccount',
1031 $fieldDefinitions = [
1033 'label-raw' => $this->msg( 'userlogin-yourname' )->escaped() . $secureLoginLink,
1035 'placeholder-message' => 'userlogin-yourname-ph',
1038 'id' => 'wpPassword1',
1039 'placeholder-message' => 'userlogin-yourpassword-ph',
1044 // option for saving the user token to a cookie
1046 'name' => 'wpRemember',
1047 'label-message' => $this->msg( 'userlogin-remembermypassword' )
1048 ->numParams( $expirationDays ),
1049 'id' => 'wpRemember',
1054 'default' => $this->msg( 'pt-login-' . $continuePart . 'button' )->text(),
1055 'id' => 'wpLoginAttempt',
1058 'linkcontainer' => [
1061 'cssclass' => 'mw-form-related-link-container mw-userlogin-help',
1062 // 'id' => 'mw-userlogin-help', // FIXME HTMLInfoField ignores this
1064 'default' => Html
::element( 'a', [
1065 'href' => Skin
::makeInternalOrExternalUrl( wfMessage( 'helplogin-url' )
1066 ->inContentLanguage()
1068 ], $this->msg( 'userlogin-helplink2' )->text() ),
1071 // button for ResetPasswordSecondaryAuthenticationProvider
1079 $fieldDefinitions['username'] +
= [
1082 'cssclass' => 'loginText',
1084 // 'required' => true,
1086 $fieldDefinitions['password'] +
= [
1087 'type' => 'password',
1088 // 'label-message' => 'userlogin-yourpassword', // would override the changepassword label
1089 'name' => 'wpPassword',
1090 'cssclass' => 'loginPassword',
1092 // 'required' => true,
1095 if ( $template->get( 'header' ) ||
$template->get( 'formheader' ) ) {
1096 // B/C for old extensions that haven't been converted to AuthManager (or have been
1097 // but somebody is using the old version) and still use templates via the
1098 // UserCreateForm/UserLoginForm hook.
1099 // 'header' used by ConfirmEdit, ConfirmAccount, Persona, WikimediaIncubator, SemanticSignup
1100 // 'formheader' used by MobileFrontend
1101 $fieldDefinitions['header'] = [
1104 'default' => $template->get( 'header' ) ?
: $template->get( 'formheader' ),
1108 if ( $this->mEntryError
) {
1109 $fieldDefinitions['entryError'] = [
1111 'default' => Html
::rawElement( 'div', [ 'class' => $this->mEntryErrorType
. 'box', ],
1112 $this->mEntryError
),
1118 if ( !$this->showExtraInformation() ) {
1119 unset( $fieldDefinitions['linkcontainer'], $fieldDefinitions['signupend'] );
1121 if ( $this->isSignup() && $this->showExtraInformation() ) {
1122 // blank signup footer for site customization
1123 // uses signupend-https for HTTPS requests if it's not blank, signupend otherwise
1124 $signupendMsg = $this->msg( 'signupend' );
1125 $signupendHttpsMsg = $this->msg( 'signupend-https' );
1126 if ( !$signupendMsg->isDisabled() ) {
1127 $usingHTTPS = $this->getRequest()->getProtocol() === 'https';
1128 $signupendText = ( $usingHTTPS && !$signupendHttpsMsg->isBlank() )
1129 ?
$signupendHttpsMsg ->parse() : $signupendMsg->parse();
1130 $fieldDefinitions['signupend'] = [
1133 'default' => Html
::rawElement( 'div', [ 'id' => 'signupend' ], $signupendText ),
1138 if ( !$this->isSignup() && $this->showExtraInformation() ) {
1139 $passwordReset = new PasswordReset( $this->getConfig(), AuthManager
::singleton() );
1140 if ( $passwordReset->isAllowed( $this->getUser() )->isGood() ) {
1141 $fieldDefinitions['passwordReset'] = [
1144 'cssclass' => 'mw-form-related-link-container',
1145 'default' => $this->getLinkRenderer()->makeLink(
1146 SpecialPage
::getTitleFor( 'PasswordReset' ),
1147 $this->msg( 'userlogin-resetpassword-link' )->text()
1153 // Don't show a "create account" link if the user can't.
1154 if ( $this->showCreateAccountLink() ) {
1155 // link to the other action
1156 $linkTitle = $this->getTitleFor( $this->isSignup() ?
'Userlogin' : 'CreateAccount' );
1157 $linkq = $this->getReturnToQueryStringFragment();
1158 // Pass any language selection on to the mode switch link
1159 if ( $this->mLanguage
) {
1160 $linkq .= '&uselang=' . urlencode( $this->mLanguage
);
1162 $loggedIn = $this->getUser()->isLoggedIn();
1164 $fieldDefinitions['createOrLogin'] = [
1167 'linkQuery' => $linkq,
1168 'default' => function ( $params ) use ( $loggedIn, $linkTitle ) {
1169 return Html
::rawElement( 'div',
1170 [ 'id' => 'mw-createaccount' . ( !$loggedIn ?
'-cta' : '' ),
1171 'class' => ( $loggedIn ?
'mw-form-related-link-container' : 'mw-ui-vform-field' ) ],
1172 ( $loggedIn ?
'' : $this->msg( 'userlogin-noaccount' )->escaped() )
1173 . Html
::element( 'a',
1175 'id' => 'mw-createaccount-join' . ( $loggedIn ?
'-loggedin' : '' ),
1176 'href' => $linkTitle->getLocalURL( $params['linkQuery'] ),
1177 'class' => ( $loggedIn ?
'' : 'mw-ui-button' ),
1181 $loggedIn ?
'userlogin-createanother' : 'userlogin-joinproject'
1191 $fieldDefinitions = $this->getBCFieldDefinitions( $fieldDefinitions, $template );
1192 $fieldDefinitions = array_filter( $fieldDefinitions );
1194 return $fieldDefinitions;
1198 * Adds fields provided via the deprecated UserLoginForm / UserCreateForm hooks
1199 * @param array $fieldDefinitions
1200 * @param FakeAuthTemplate $template
1203 protected function getBCFieldDefinitions( $fieldDefinitions, $template ) {
1204 if ( $template->get( 'usedomain', false ) ) {
1205 // TODO probably should be translated to the new domain notation in AuthManager
1206 $fieldDefinitions['domain'] = [
1208 'label-message' => 'yourdomainname',
1209 'options' => array_combine( $template->get( 'domainnames', [] ),
1210 $template->get( 'domainnames', [] ) ),
1211 'default' => $template->get( 'domain', '' ),
1212 'name' => 'wpDomain',
1213 // FIXME id => 'mw-user-domain-section' on the parent div
1217 // poor man's associative array_splice
1218 $extraInputPos = array_search( 'extrainput', array_keys( $fieldDefinitions ), true );
1219 $fieldDefinitions = array_slice( $fieldDefinitions, 0, $extraInputPos, true )
1220 +
$template->getExtraInputDefinitions()
1221 +
array_slice( $fieldDefinitions, $extraInputPos +
1, null, true );
1223 return $fieldDefinitions;
1227 * Check if a session cookie is present.
1229 * This will not pick up a cookie set during _this_ request, but is meant
1230 * to ensure that the client is returning the cookie which was set on a
1231 * previous pass through the system.
1235 protected function hasSessionCookie() {
1236 global $wgDisableCookieCheck, $wgInitialSessionId;
1238 return $wgDisableCookieCheck ||
(
1239 $wgInitialSessionId &&
1240 $this->getRequest()->getSession()->getId() === (string)$wgInitialSessionId
1245 * Returns a string that can be appended to the URL (without encoding) to preserve the
1246 * return target. Does not include leading '?'/'&'.
1249 protected function getReturnToQueryStringFragment() {
1251 if ( $this->mReturnTo
!== '' ) {
1252 $returnto = 'returnto=' . wfUrlencode( $this->mReturnTo
);
1253 if ( $this->mReturnToQuery
!== '' ) {
1254 $returnto .= '&returntoquery=' . wfUrlencode( $this->mReturnToQuery
);
1261 * Whether the login/create account form should display a link to the
1262 * other form (in addition to whatever the skin provides).
1265 private function showCreateAccountLink() {
1266 if ( $this->isSignup() ) {
1268 } elseif ( $this->getUser()->isAllowed( 'createaccount' ) ) {
1275 protected function getTokenName() {
1276 return $this->isSignup() ?
'wpCreateaccountToken' : 'wpLoginToken';
1280 * Produce a bar of links which allow the user to select another language
1281 * during login/registration but retain "returnto"
1285 protected function makeLanguageSelector() {
1286 $msg = $this->msg( 'loginlanguagelinks' )->inContentLanguage();
1287 if ( $msg->isBlank() ) {
1290 $langs = explode( "\n", $msg->text() );
1292 foreach ( $langs as $lang ) {
1293 $lang = trim( $lang, '* ' );
1294 $parts = explode( '|', $lang );
1295 if ( count( $parts ) >= 2 ) {
1296 $links[] = $this->makeLanguageSelectorLink( $parts[0], trim( $parts[1] ) );
1300 return count( $links ) > 0 ?
$this->msg( 'loginlanguagelabel' )->rawParams(
1301 $this->getLanguage()->pipeList( $links ) )->escaped() : '';
1305 * Create a language selector link for a particular language
1306 * Links back to this page preserving type and returnto
1308 * @param string $text Link text
1309 * @param string $lang Language code
1312 protected function makeLanguageSelectorLink( $text, $lang ) {
1313 if ( $this->getLanguage()->getCode() == $lang ) {
1314 // no link for currently used language
1315 return htmlspecialchars( $text );
1317 $query = [ 'uselang' => $lang ];
1318 if ( $this->mReturnTo
!== '' ) {
1319 $query['returnto'] = $this->mReturnTo
;
1320 $query['returntoquery'] = $this->mReturnToQuery
;
1324 $targetLanguage = Language
::factory( $lang );
1325 $attr['lang'] = $attr['hreflang'] = $targetLanguage->getHtmlCode();
1327 return $this->getLinkRenderer()->makeKnownLink(
1328 $this->getPageTitle(),
1335 protected function getGroupName() {
1340 * @param array &$formDescriptor
1341 * @param array $requests
1343 protected function postProcessFormDescriptor( &$formDescriptor, $requests ) {
1344 // Pre-fill username (if not creating an account, T46775).
1346 isset( $formDescriptor['username'] ) &&
1347 !isset( $formDescriptor['username']['default'] ) &&
1350 $user = $this->getUser();
1351 if ( $user->isLoggedIn() ) {
1352 $formDescriptor['username']['default'] = $user->getName();
1354 $formDescriptor['username']['default'] =
1355 $this->getRequest()->getSession()->suggestLoginUsername();
1359 // don't show a submit button if there is nothing to submit (i.e. the only form content
1360 // is other submit buttons, for redirect flows)
1361 if ( !$this->needsSubmitButton( $requests ) ) {
1362 unset( $formDescriptor['createaccount'], $formDescriptor['loginattempt'] );
1365 if ( !$this->isSignup() ) {
1366 // FIXME HACK don't focus on non-empty field
1367 // maybe there should be an autofocus-if similar to hide-if?
1369 isset( $formDescriptor['username'] )
1370 && empty( $formDescriptor['username']['default'] )
1371 && !$this->getRequest()->getCheck( 'wpName' )
1373 $formDescriptor['username']['autofocus'] = true;
1374 } elseif ( isset( $formDescriptor['password'] ) ) {
1375 $formDescriptor['password']['autofocus'] = true;
1379 $this->addTabIndex( $formDescriptor );
1384 * B/C class to try handling login/signup template modifications even though login/signup does not
1385 * actually happen through a template anymore. Just collects extra field definitions and allows
1386 * some other class to do decide what to do with threm..
1387 * TODO find the right place for adding extra fields and kill this
1389 class FakeAuthTemplate
extends BaseTemplate
{
1390 public function execute() {
1391 throw new LogicException( 'not used' );
1395 * Extensions (AntiSpoof and TitleBlacklist) call this in response to
1396 * UserCreateForm hook to add checkboxes to the create account form.
1397 * @param string $name
1398 * @param string $value
1399 * @param string $type
1400 * @param string $msg
1401 * @param string|bool $helptext
1403 public function addInputItem( $name, $value, $type, $msg, $helptext = false ) {
1404 // use the same indexes as UserCreateForm just in case someone adds an item manually
1405 $this->data
['extrainput'][] = [
1410 'helptext' => $helptext,
1415 * Turns addInputItem-style field definitions into HTMLForm field definitions.
1418 public function getExtraInputDefinitions() {
1421 foreach ( $this->get( 'extrainput', [] ) as $field ) {
1423 'type' => $field['type'] === 'checkbox' ?
'check' : $field['type'],
1424 'name' => $field['name'],
1425 'value' => $field['value'],
1426 'id' => $field['name'],
1428 if ( $field['msg'] ) {
1429 $definition['label-message'] = $this->getMsg( $field['msg'] );
1431 if ( $field['helptext'] ) {
1432 $definition['help'] = $this->msgWiki( $field['helptext'] );
1435 // the array key doesn't matter much when name is defined explicitly but
1436 // let's try and follow HTMLForm conventions
1437 $name = preg_replace( '/^wp(?=[A-Z])/', '', $field['name'] );
1438 $definitions[$name] = $definition;
1441 if ( $this->haveData( 'extrafields' ) ) {
1442 $definitions['extrafields'] = [
1445 'default' => $this->get( 'extrafields' ),
1449 return $definitions;
1454 * LoginForm as a special page has been replaced by SpecialUserLogin and SpecialCreateAccount,
1455 * but some extensions called its public methods directly, so the class is retained as a
1456 * B/C wrapper. Anything that used it before should use AuthManager instead.
1458 class LoginForm
extends SpecialPage
{
1462 const WRONG_PLUGIN_PASS
= 3;
1463 const NOT_EXISTS
= 4;
1464 const WRONG_PASS
= 5;
1465 const EMPTY_PASS
= 6;
1466 const RESET_PASS
= 7;
1468 const CREATE_BLOCKED
= 9;
1469 const THROTTLED
= 10;
1470 const USER_BLOCKED
= 11;
1471 const NEED_TOKEN
= 12;
1472 const WRONG_TOKEN
= 13;
1473 const USER_MIGRATED
= 14;
1475 public static $statusCodes = [
1476 self
::SUCCESS
=> 'success',
1477 self
::NO_NAME
=> 'no_name',
1478 self
::ILLEGAL
=> 'illegal',
1479 self
::WRONG_PLUGIN_PASS
=> 'wrong_plugin_pass',
1480 self
::NOT_EXISTS
=> 'not_exists',
1481 self
::WRONG_PASS
=> 'wrong_pass',
1482 self
::EMPTY_PASS
=> 'empty_pass',
1483 self
::RESET_PASS
=> 'reset_pass',
1484 self
::ABORTED
=> 'aborted',
1485 self
::CREATE_BLOCKED
=> 'create_blocked',
1486 self
::THROTTLED
=> 'throttled',
1487 self
::USER_BLOCKED
=> 'user_blocked',
1488 self
::NEED_TOKEN
=> 'need_token',
1489 self
::WRONG_TOKEN
=> 'wrong_token',
1490 self
::USER_MIGRATED
=> 'user_migrated',
1494 * @param WebRequest $request
1496 public function __construct( $request = null ) {
1497 wfDeprecated( 'LoginForm', '1.27' );
1498 parent
::__construct();
1502 * @deprecated since 1.27 - call LoginHelper::getValidErrorMessages instead.
1505 public static function getValidErrorMessages() {
1506 return LoginHelper
::getValidErrorMessages();
1510 * @deprecated since 1.27 - don't use LoginForm, use AuthManager instead
1511 * @param string $username
1512 * @return array|false
1514 public static function incrementLoginThrottle( $username ) {
1515 wfDeprecated( __METHOD__
, "1.27" );
1517 $username = User
::getCanonicalName( $username, 'usable' ) ?
: $username;
1518 $throttler = new Throttler();
1519 return $throttler->increase( $username, $wgRequest->getIP(), __METHOD__
);
1523 * @deprecated since 1.27 - don't use LoginForm, use AuthManager instead
1524 * @param string $username
1527 public static function incLoginThrottle( $username ) {
1528 wfDeprecated( __METHOD__
, "1.27" );
1529 $res = self
::incrementLoginThrottle( $username );
1530 return is_array( $res ) ?
true : 0;
1534 * @deprecated since 1.27 - don't use LoginForm, use AuthManager instead
1535 * @param string $username
1538 public static function clearLoginThrottle( $username ) {
1539 wfDeprecated( __METHOD__
, "1.27" );
1541 $username = User
::getCanonicalName( $username, 'usable' ) ?
: $username;
1542 $throttler = new Throttler();
1543 return $throttler->clear( $username, $wgRequest->getIP() );
1547 * @deprecated since 1.27 - don't use LoginForm, use AuthManager instead
1549 public static function getLoginToken() {
1550 wfDeprecated( __METHOD__
, '1.27' );
1552 return $wgRequest->getSession()->getToken( '', 'login' )->toString();
1556 * @deprecated since 1.27 - don't use LoginForm, use AuthManager instead
1558 public static function setLoginToken() {
1559 wfDeprecated( __METHOD__
, '1.27' );
1563 * @deprecated since 1.27 - don't use LoginForm, use AuthManager instead
1565 public static function clearLoginToken() {
1566 wfDeprecated( __METHOD__
, '1.27' );
1568 $wgRequest->getSession()->resetToken( 'login' );
1572 * @deprecated since 1.27 - don't use LoginForm, use AuthManager instead
1575 public static function getCreateaccountToken() {
1576 wfDeprecated( __METHOD__
, '1.27' );
1578 return $wgRequest->getSession()->getToken( '', 'createaccount' )->toString();
1582 * @deprecated since 1.27 - don't use LoginForm, use AuthManager instead
1584 public static function setCreateaccountToken() {
1585 wfDeprecated( __METHOD__
, '1.27' );
1589 * @deprecated since 1.27 - don't use LoginForm, use AuthManager instead
1591 public static function clearCreateaccountToken() {
1592 wfDeprecated( __METHOD__
, '1.27' );
1594 $wgRequest->getSession()->resetToken( 'createaccount' );